const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const app = new express();

//  注意app.all要写在  app.use之前
app.all("*", function (req, res, next) {
  //设置允许跨域的域名，*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", "*");
  //允许的header类型
  res.header("Access-Control-Allow-Headers", "content-type");
  //跨域允许的请求方式
  res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
  if (req.method.toLowerCase() == "options")
    res.send(200); //让options尝试请求快速结束
  else next();
});

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// 数据库连接参数
const dbConfig = {
  host: "share_mysql",
  // host: "localhost",
  user: "root",
  password: "123456",
  database: "docker_share",
};

// 接口定义
app.get("/get_user", (req, res) => {
  console.log("get_user服务收到请求");
  const conn = mysql.createConnection(dbConfig); //连接数据库
  try {
    conn.query("select * from  Users;", null, (_, results) => {
      res.send({
        code: 200,
        message: "用户查询成功！",
        data: results,
      });
    });
  } catch {
    res.send({
      code: 500,
      message: "数据添加失败！",
      data: [],
    });
  }

  conn.end((err) => {
    //关闭数据库
    if (err) {
      console.error(err.stack);
      return;
    }
  });
});

// 启动服务
app.listen(8002, (err) => {
  if (!err) console.log("【查看用户服务】服务器启动了");
});
